<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <div class="title">欢迎登录</div>
      <el-form
        :model="user"
        :rules="rules"
        ref="loginForm"
        class="login-form"
        label-width="0"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="user.userName"
            placeholder="登录账号"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="user.password"
            type="password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item prop="verifyCode">
          <el-input
            v-model="user.verifyCode"
            placeholder="验证码"
            clearable
            style="width: 60%"
          />
          <canvas
            ref="canvasRef"
            class="captcha"
            @click="refreshCaptcha"
            width="100"
            height="40"
          ></canvas>
        </el-form-item>

        <el-form-item class="actions">
          <el-row justify="space-between" align="middle" style="display:flex;flex-wrap:nowrap;width:100%;">
            <el-col :span="8" style="flex:none;">
              <el-checkbox v-model="user.remember">记住我</el-checkbox>
            </el-col>
            <el-col :span="8" style="flex:none;text-align:right;">
              <a class="forgot" @click.prevent="onForgot">忘记密码？</a>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="login"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { inject, ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import qs from 'qs';
import { jwtDecode } from 'jwt-decode'

// 路由与 axios
const router = useRouter();
const axios = inject('axios');

// 用户数据和校验规则
const user = reactive({
  userName: '',
  password: '',
  verifyCode: '',
  remember: false,
});

// 验证码逻辑
const captchaText = ref('');
const canvasRef = ref(null);

function randomText(len = 4) {
	const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
	let s = '';
  for (let i = 0; i < len; i++) {
    s += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return s;
}

function drawCaptcha() {
  const ctx = canvasRef.value.getContext('2d');
  ctx.clearRect(0, 0, 100, 40);
  ctx.fillStyle = '#f2f2f2';
  ctx.fillRect(0, 0, 100, 40);
  ctx.font = '24px Arial';
  ctx.fillStyle = '#333';
  ctx.fillText(captchaText.value, 10, 28);
}

function refreshCaptcha() {
  captchaText.value = randomText();
  drawCaptcha();
}

function validateCaptcha(rule, value, callback) {
  if (!value) {
    callback(new Error('请输入验证码'));
  } else if (value.toUpperCase() !== captchaText.value) {
    callback(new Error('验证码错误'));
  } else {
    callback();
  }
}

// 表单 rules
const rules = {
  userName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  verifyCode: [{ validator: validateCaptcha, trigger: 'blur' }],
};

const loginForm = ref(null);
const loading = ref(false);

onMounted(() => {
  refreshCaptcha();
});

function onForgot() {
  ElMessage.info('请联系管理员重置密码');
}

// 原 login 方法：先校验验证码，再请求登录
function login() {
  loginForm.value.validate(valid => {
    if (!valid) return;
    loading.value = true;
    // 验证码已在 rules 中处理, 直接调用原逻辑
    let url = 'UserController/login';
    axios
      .post(url, qs.stringify({ userName: user.userName, password: user.password }))
      .then(response => {
        let rb = response.data;
        if (rb.status == 200) {
          let token = rb.data;
          sessionStorage.setItem('token', token);
		  const payload = jwtDecode(token);
		  const user = JSON.parse(payload.mobileJson)
		  if(user.role==0){
			  router.push('/menu');
		  }else{
			  router.push('/menu1');
		  }
          
        } else {
          alert(rb.msg);
          refreshCaptcha();
        }
      })
      .catch(error => {
        console.log(error);
        refreshCaptcha();
      })
      .finally(() => (loading.value = false));
  });
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #6b8ce3 0%, #88b4f5 100%);
}
.login-card {
  width: 380px;
  padding: 30px 20px;
  border-radius: 12px;
}
.title {
  font-size: 26px;
  font-weight: bold;
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}
.login-form ::v-deep .el-input__inner {
  border-radius: 6px;
}
.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.forgot {
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
}
.forgot:hover {
  text-decoration: underline;
}
.login-button {
  width: 100%;
  border-radius: 6px;
}
.captcha {
  vertical-align: middle;
  margin-left: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}
</style>
